package com.fas.core.plugin.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.util.ByteSource;

import com.fas.hehe.system.model.LoginUser;
import com.fas.hehe.system.model.User;
import com.fas.hehe.system.service.UserService;
/**
 * 
 * 通过mobile登录认证
 *
 * @Copyright: Copyright (c) 2016 FAS 
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月10日 上午12:52:36
 * @version V1.0
 */
public class MobileRealm extends BaseRealm {


	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {

		String mobile = (String) token.getPrincipal();

		userService = new UserService();
		User user = userService.findByMobile(mobile);

		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}

		if (Boolean.TRUE.equals(user.getLocked())) {
			throw new LockedAccountException(); // 帐号锁定
		}

		LoginUser loginUser = this.createLoginUser(user,
				LoginUser.LoginBy.MOBILE);

		// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				loginUser, // 登录用户
				user.getPassword(), // 密码
				ByteSource.Util.bytes(user.getUsername() + user.getSalt()),// salt=username+salt
				getName() // realm name
		);

		return authenticationInfo;
	}

}
